<template>
  <div>
    <div v-if="type == 'text'" class="wrap">
      <input type="text" v-maxLength="maxLen" v-model="value" />
      <span class="span">0/{{ maxLen }}</span>
    </div>
    <div v-else-if="type == 'textarea'" class="wrap">
      <textarea
        cols="30"
        rows="10"
        v-maxLength="maxLen"
        v-model="value"
      ></textarea>
      <span class="textareaSpan">0/{{ maxLen }}</span>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    type: {
      default: "text",
      type: String || Number,
    },
    maxLen: {
      default: 10,
      type: String || Number,
    },
  },
  data() {
    return {
      value: "",
    };
  },
  directives: {
    maxLength: {
      inserted(el, binding) {
        el.setAttribute("maxlength", binding.value);
      },
      update(el, binding) {
        let valLen = el.value.length;
        let span = el.parentElement.children[1];
        span.innerHTML = `${valLen}/${binding.value}`;
        // console.log(binding);

        if (valLen == binding.value) {
          el.style.color = "coral";
        } else {
          el.style.color = "";
        }
      },
    },
  },
};
</script>

<style>
.wrap {
  display: inline-block;
  position: relative;
}

.span {
  position: absolute;
  right: 5px;
  top: 4px;
  font-size: 10px;
  color: #999;
}

.textareaSpan {
  position: absolute;
  right: 10px;
  bottom: 10px;
}
</style>